<?php
// +----------------------------------------------------------------------
// | Copyright © Sogu Technologies Co. Ltd 2018-2050 All rights reserved.
// +----------------------------------------------------------------------
// | File name: Repay.php
// +----------------------------------------------------------------------
// | Author: ljf
// +----------------------------------------------------------------------
// | Description: 后台还款逻辑trait
// +----------------------------------------------------------------------
// | Others: 其他内容的说明
// +----------------------------------------------------------------------
// | History: 修改历史记录列表，每条修改记录应包含修改日期、修改者及修改内容简述
// +----------------------------------------------------------------------
// | 1.Date: 2019/1/10 Author: ljf Modification: 创建
// +----------------------------------------------------------------------

namespace App\Models\Traits;

use App\Models\RepayRecord;
use App\Models\RepayRecordMoney;
use App\Models\RepaySummary;
use App\Models\UserBankCard;
use App\Models\UserCertOcr;
use App\Models\UserDeviceInfo;
use App\Models\UserInfo;
use Illuminate\Support\Carbon;

trait RepayInfo
{

    /**
     * 通过借款id获取借款的详细信息
     * @param $loanId 借款id
     */
    public static function getRepayAllInfo($loan_request_id){
        if(!$loan_request_id){
            return [];
        }
        //获取summary的列表和对应的记录
        $repayInfo = self::with(['recordMany'=>function($q){
            $q->where('period','<>',0);
        },'recordMany.month','recordMany.common','recordMany.money'])
            ->where('loan_request_id',$loan_request_id)
            ->first();

        if(!isset($repayInfo->recordMany)){
            return [];
        }
        //如果有全部还清的记录  那就获取到
        $allRepaymentLog = self::with(['recordOne'=>function($q){
            $q->where('period','=',0);
            $q->where('status','=',RepayRecord::STATUS_FOUR);
        },'recordOne.month','recordOne.common','recordOne.money'])
            ->where('loan_request_id',$loan_request_id)
            ->first();
        $recordInfo = $repayInfo->recordMany;
        //在2019.03.13数据迁移,老数据没有0这条记录,所有要在分记录中查出金额
        $recordAllInfo = isset($allRepaymentLog->recordOne) ? $allRepaymentLog->recordOne : '';
        $returnData = array();

        $returnKey = 0;
        $flag = true;
        foreach ($recordInfo as $k => $v){
            $data = array();
            $data['type'] = self::getRepayType($v->status,$v->normal_date);//1 待还 2 逾期 3 已还 5 还清
            $data['money'] = $v->amount;//本金
            $data['lending_money'] = bcadd($v->common->lending_money,$v->money->lending_money,2);//利息
            $data['manage_money'] = $v->common->manage_money;//应还管理费
            $data['fines_money'] = $data['type'] != RepayRecord::RETURN_TYPE_TWO ? bcadd($v->common->fines_money,$v->money->fines_money,2) : self::getFinesMoney($v->normal_date,$repayInfo->rate['fines_rate'],$repayInfo->amount,$v->common->id); //应还罚息
            if($v->pay_off == RepayRecord::PAY_OFF_ONE){
                $data['repayment_money'] = $v->money->repayment_money;//手续费
            }elseif($v->pay_off == RepayRecord::PAY_OFF_TWO){
                $data['repayment_money'] = bcadd($v->common->repayment_money,$v->money->repayment_money,2);//手续费
            }
            $data['month_money'] = $v->month->amount;//月保费
            $data['all_money'] = bcadd(bcadd(bcadd(bcadd(bcadd($data['money'],$data['lending_money'],2),$data['manage_money'],2),$data['fines_money'],2),$data['repayment_money'],2),$data['month_money'],2);//应还合计
            $data['normal_date'] = $v->normal_date;//应还合计
            $data['use_card'] = 0;//使用卡卷
            $data['repay_date'] = $v->repay_date;//实还日期
            $data['repay_type'] = $v->money->type;//类型已资方的接口为准,还款方式(提前还款 正常还款 逾期还款 全部还清)
            $data['repay_card'] = UserBankCard::getCardNumById($v->bank_cards_id);//还款方式

            if($recordAllInfo && $v->status == RepayRecord::STATUS_FOUR && $flag && $v->pay_off == RepayRecord::PAY_OFF_TWO){
                //如果有全部还清这条记录,就把全部还清这条记录替换在哪期开始全部还清的数据上,替换一下
                $flag = false;
                self::setRepayData($data,$recordAllInfo);
            }elseif($recordAllInfo && $flag == false && $v->status == RepayRecord::STATUS_FOUR && $v->pay_off == RepayRecord::PAY_OFF_TWO){
                $data['repay_type'] = 0;
            }

            $returnData[$returnKey] = $data;
            $returnKey++;
        }
        return $returnData;
    }

    /**
     * Description:后台判断是否有summary_id
     * Author:lijiafei
     * @param $summary_id
     * @return int
     */
    protected static function isAllRepayBackend($summary_id){
        $flag = RepayRecord::where([
            'summary_id' => $summary_id,
            'status' => RepayRecord::STATUS_FOUR,
            'pay_off' => RepayRecord::PAY_OFF_TWO,
        ])->where('period','<>',0)->first();
        if(isset($flag) && !empty($flag)){
            return 1;
        }else{
            return 0;
        }
    }

    /**
     * 获取状态
     * @param $status 1 待还 2 还款中 3 失败 4 成功
     * @return $type 1 待还 2 逾期 3 已还
     */
    public static function getRepayType($status,$normal_date){
        $type = 0;
        if($status == RepayRecord::STATUS_ONE){//待还
            $type = RepayRecord::RETURN_TYPE_ONE;//待还
            //判断是否过期
            $day = count_days(Carbon::now()->toDateString(),$normal_date);
            if($day > 0){
                $type = RepayRecord::RETURN_TYPE_TWO;//逾期
            }
        }elseif($status == RepayRecord::STATUS_TWO || $status == RepayRecord::STATUS_THREE){//还款中,失败
            $type = RepayRecord::RETURN_TYPE_ONE;//待还
        }elseif($status == RepayRecord::STATUS_FOUR){//成功
            $type = RepayRecord::RETURN_TYPE_THREE;//已还

        }
        return $type;
    }

    /**
     * 获取公共的罚息和资方的罚息
     * @param $normal_date 应还日期
     * @param $finesRate 逾期罚息
     * @param $amount 借款总金额
     * @param $loanId 借款id
     * @param $period 当前期数
     * @return $fines_money 罚息
     */
    public static function getFinesMoney($normal_date,$finesRate,$amount,$common_id){
        $fines_money = self::getFines($normal_date,$finesRate,$amount,$common_id);
        $commonFinesMoney = $fines_money['common_fines_money'];
        $moneyFinesMoney = $fines_money['money_fines_money'];
        $fines_money = bcadd($commonFinesMoney,$moneyFinesMoney,2);
        return $fines_money;
    }

    public static function setRepayData(&$data,$recordAllInfo){
        $data['amount'] = $recordAllInfo->amount;
        $data['lending_money'] = bcadd($recordAllInfo->common->lending_money,$recordAllInfo->money->lending_money,2);//利息
        $data['manage_money'] = $recordAllInfo->common->manage_money;//应还管理费
        $data['fines_money'] = bcadd($recordAllInfo->common->fines_money,$recordAllInfo->money->fines_money,2); //应还罚息
        $data['repayment_money'] = bcadd($recordAllInfo->common->repayment_money,$recordAllInfo->money->repayment_money,2);//手续费
        $data['month_money'] = $recordAllInfo->month->amount;//月保费
        $data['all_money'] = bcadd(bcadd(bcadd(bcadd(bcadd($data['amount'],$data['lending_money'],2),$data['manage_money'],2),$data['fines_money'],2),$data['repayment_money'],2),$data['month_money'],2);//应还合计
        $data['normal_date'] = $recordAllInfo->normal_date;//应还合计
        $data['use_card'] = 0;//使用卡卷
        $data['repay_date'] = $recordAllInfo->repay_date;//实还日期
        $data['repay_type'] = $recordAllInfo->money->type;// type 类型还款方式(提前还款 正常还款 逾期还款 全部还清)
        $data['repay_card'] = UserBankCard::getCardNumById($recordAllInfo->bank_cards_id);//还款方式
    }


    /**
     * 获取列表
     * status 1 借款中 2 完成 借款状态
     * type 细分状态 1 待还 5 逾期 3 正常还款 4 全部还清
     * 用户名
     */
    public static function getRepayList($status,$type,$name,$page_size = 20){
        $back = new RepaySummary();
        $back->setConnection('backend');
        $info =$back->query()
            ->select('repay_records.id','repay_records.summary_id','repay_records.uid','user_cert_ocrs.name as name','user_cert_ocrs.num as num','repay_records.status','repay_records.pay_off','normal_date','repay_date','users.phone_num','users.source')
            ->where('current_repay',RepaySummary::CURRENT_REPAY_ONE)//获取当前的操作期数
            ->where('user_cert_ocrs.is_valid',UserCertOcr::IS_VALID)
            ->leftjoin('user_cert_ocrs','user_cert_ocrs.user_id','repay_summaries.uid')
            ->leftjoin('users','users.id','repay_summaries.uid')
            ->leftjoin('repay_records',function($q){
                $q->On('repay_records.summary_id', '=', 'repay_summaries.id')->On('repay_records.period', '=', 'repay_summaries.period');
            })
            ->when($status, function ($query) use ($status) {
                return $query->where('repay_summaries.status', $status);
            })
            ->when($name, function ($query) use ($name) {
                return $query->where('user_cert_ocrs.name', $name);
            })
            ->when($type, function ($query) use ($type) {
                switch ($type){//1 待还 5 逾期 2 正常还款 4 全部还清
                    case RepayRecordMoney::TYPE_ONE:
                        $query->whereIn('repay_records.status',[RepayRecord::STATUS_ONE,RepayRecord::STATUS_TWO,RepayRecord::STATUS_THREE]);
                        break;
                    case RepayRecordMoney::TYPE_FIVE:
                        $query->where('repay_records.normal_date','<=',Carbon::now()->toDateString());
                        $query->where('repay_records.status','<>',RepayRecord::STATUS_FOUR);
                        break;
                    case RepayRecordMoney::TYPE_TWO:
                        $query->where('repay_records.pay_off','=',RepayRecord::PAY_OFF_ONE);
                        $query->where('repay_summaries.status','=',RepaySummary::STATUS_TWO);
                        break;
                    case RepayRecordMoney::TYPE_FOUR:
                        $query->where('repay_records.pay_off','=',RepayRecord::PAY_OFF_TWO);
                        $query->where('repay_summaries.status','=',RepaySummary::STATUS_TWO);
                        break;
                }
            });
        $data = $info->paginate($page_size)->toArray();
        $returnData['list'] = self::getData($data['data']);
        $returnData['total'] = $data['total'];
        return $returnData;
    }

    protected static function getData($data){
        if(!$data){
            return [];
        }
        foreach ($data as $k => &$v){
            $summaryInfo = self::select('status','uid','loan_id','amount','period_count')->where('id',$v['summary_id'])->first();
            $v['summary_status'] = $summaryInfo['status'];
            $v['count'] = self::where('uid',$summaryInfo['uid'])->count();
            $v['loan_id'] = $summaryInfo['loan_id'];
            $v['amount'] = $summaryInfo['amount'];
            $v['period_count'] = $summaryInfo['period_count'];

            //判断type的状态
            if($v['status'] != RepayRecord::STATUS_FOUR){
                $v['type'] = RepayRecordMoney::TYPE_ONE;
            }elseif(count_days(Carbon::now()->toDateString(),$v['normal_date']) > 0 && $v['status'] == RepayRecord::STATUS_FOUR && $v['pay_off'] == RepayRecord::PAY_OFF_ONE){
                $v['type'] = RepayRecordMoney::TYPE_FIVE;
            }elseif($v['pay_off'] == RepayRecord::PAY_OFF_ONE && $v['status'] == RepayRecord::STATUS_FOUR){
                $v['type'] = RepayRecordMoney::TYPE_TWO;
            }elseif($v['pay_off'] == RepayRecord::PAY_OFF_TWO && $v['status'] == RepayRecord::STATUS_FOUR){
                $v['type'] = RepayRecordMoney::TYPE_FOUR;
            }
            unset($v['summary_id']);
            unset($v['status']);
            unset($v['pay_off']);
        }
        return $data;
    }

    /**
     * 获取用户列表
     */
    public static function getUserInfo($uid,$page_size){

        $back = new RepaySummary();
        $back->setConnection('backend');
        $info =$back->query()
            ->select('repay_summaries.id','repay_summaries.loan_request_id','repay_summaries.uid','repay_summaries.created_at','users.phone_num','users.source','user_cert_ocrs.name','user_wechats.openid','repay_records.pay_off','repay_records.normal_date','repay_summaries.status as summary_status','repay_records.status as record_status','user_cert_ocrs.num','user_cert_ocrs.domicile_address','user_cert_ocrs.issuing_authority','user_cert_ocrs.valid_date_begin','user_cert_ocrs.valid_date_end')
            ->leftjoin('repay_records',function($q){
                $q->On('repay_records.summary_id', '=', 'repay_summaries.id')->On('repay_records.period', '=', 'repay_summaries.period');
            })
            ->leftjoin('users','users.id','repay_summaries.uid')
            ->leftjoin('user_cert_ocrs','user_cert_ocrs.user_id','repay_summaries.uid')
            ->leftjoin('user_wechats','user_wechats.uid','repay_summaries.uid')
            ->where('repay_summaries.uid',$uid)
            ->where('user_cert_ocrs.is_valid',UserCertOcr::IS_VALID)
            ->orderByDesc('repay_summaries.id')->paginate()->toArray();
        $returnData['list'] = self::getListData($info['data']);
        $returnData['total'] = $info['total'];
        return $returnData;
    }

    protected static function getListData($data){
        if(!$data){
            return [];
        }
        $info = array();
        foreach ($data as $k => $v){
            $info[$k]['loan_time'] = date('Y-m-d',strtotime($v['created_at']));//日期
            //基础信息
            $base_info = self::getBaseInfo($v);
            $info[$k]['base_info'] = $base_info;
            //实名认证
            $real_info = self::getRealInfo($v);
            $info[$k]['real_info'] = $real_info;
            //个人信息
            $user_info = self::getUserInfos($v['uid']);
            $info[$k]['user_info'] = $user_info;
            //其他信息
            $device_info = self::getDeviceInfo($v['loan_request_id']);
            $info[$k]['device_info'] = $device_info;
            //储蓄卡
            $bank_info = self::getBankInfo($v['uid']);
            $info[$k]['bank_card_info'] = $bank_info['bank_card_info'];
            $info[$k]['credit_card_info'] = $bank_info['credit_card_info'];
        }
        return $info;
    }

    /**
     * Description:获取基础信息
     * Author:lijiafei
     * @param $v
     * @return array
     */
    protected static function getBaseInfo($v){
        $base_info = [
            'name' => $v['name'],
            'phone' => $v['phone_num'],
            'user_id' => $v['uid'],
            'source' => $v['source'],
            'openid' => $v['openid'],
        ];
        //判断status 和detail_status
        if($v['summary_status'] == RepaySummary::STATUS_TWO){
            $base_info['status'] = RepaySummary::$FULL_STATUS[RepaySummary::STATUS_TWO];
            if($v['pay_off'] == RepayRecord::PAY_OFF_TWO){
                //提前结清
                $base_info['detail_status'] = RepayRecordMoney::$TYPE_ENUM[RepayRecordMoney::TYPE_FOUR];
            }else if($v['pay_off'] == RepayRecord::PAY_OFF_ONE){
                //逐期还款
                $base_info['detail_status'] =  RepayRecordMoney::$TYPE_ENUM[RepayRecordMoney::TYPE_TWO];
            }
        }elseif($v['summary_status'] == RepaySummary::STATUS_ONE){
            $base_info['status'] = RepaySummary::$FULL_STATUS[RepaySummary::STATUS_ONE];
            if($v['record_status'] != RepayRecord::STATUS_FOUR){
                //判断是否逾期
                $day = count_days(Carbon::now()->toDateString(),$v['normal_date']);
                if($day > 0){
                    //逾期
                    $base_info['detail_status'] = RepayRecordMoney::$TYPE_ENUM[RepayRecordMoney::TYPE_FIVE];
                }else{
                    //待还
                    $base_info['detail_status'] = RepayRecordMoney::$TYPE_ENUM[RepayRecordMoney::TYPE_ONE];
                }
            }
        }
        return $base_info;
    }

    /**
     * 获取实名认证
     */
    protected static function getRealInfo($v){
        $real_info = [
            'card_num' => $v['num'],//身份证
            'issuing_authority' => $v['issuing_authority'],//签发机关
            'valid_at' => $v['valid_date_begin'] . '至' . $v['valid_date_end'],
            'domicile_address' => $v['domicile_address'],
        ];
        return $real_info;
    }

    /**
     *个人信息
     */
    protected static function getUserInfos($uid){
        $userInfos = UserInfo::where('user_id',$uid)->orderByDesc('id')->first();
        $user_info = [
            'education' => isset($userInfos['education']) ? UserInfo::$EDUCATION_ENUM[$userInfos['education']] : '',
            'company' => isset($userInfos['company']) ? $userInfos['company'] : '',
            'work_address' => isset($userInfos['work_address']) ? $userInfos['work_address'] : '',
            'work_phone' => isset($userInfos['work_phone']) ? $userInfos['work_phone']:'',
            'linkman_first' => isset($userInfos['linkman_first']) ? $userInfos['linkman_first'] : '',
            'linkman_first_relation' => isset($userInfos['linkman_first_relation']) ? UserInfo::$USER_RELATION[$userInfos['linkman_first_relation']] : '',
            'linkman_first_phone' => isset($userInfos['linkman_first_phone']) ? $userInfos['linkman_first_phone'] : '',
            'linkman_second' => isset($userInfos['linkman_second']) ? $userInfos['linkman_second'] : '',
            'linkman_second_relation' => isset($userInfos['linkman_second_relation']) ? UserInfo::$USER_RELATION[$userInfos['linkman_second_relation']] : '',
            'linkman_second_phone' => isset($userInfos['linkman_second_phone']) ? $userInfos['linkman_second_phone'] : '',
        ];
        return $user_info;
    }

    /**
     * Description:其他信息
     * Author:lijiafei
     */
    protected static function getDeviceInfo($loan_request_id){
        $deviceInfo = UserDeviceInfo::where('loan_request_id',$loan_request_id)->first();
        $device_info = [
            'phone' => '',
            'face' => '',
            'zhima' => '',
            'device_type' => $deviceInfo['device_type'],
            'gps' => $deviceInfo['gps'],
            'device' => $deviceInfo['device'],
            'device_mac' => $deviceInfo['device_mac'],
            'device_imei' => $deviceInfo['device_imei'],
            'device_uuid' => $deviceInfo['device_uuid'],
            'device_app' => $deviceInfo['device_app'],
        ];
        return $device_info;
    }

    /**
     *
     */
    protected static function getBankInfo($uid){
        $bankCard = UserBankCard::where('uid',$uid)->get();
        //储蓄卡
        $bank_card_info = array();
        $credit_card_info = array();
        foreach ($bankCard as $key => $val){
            if($val->is_credit == UserBankCard::CREDIT_NO){
                $bank_card_info[] = [
                    'name' => $val['bank_name'],
                    'bank_card_num' => $val['card_num']
                ];
            }else if($val->is_credit == UserBankCard::CREDIT_YES){
                $credit_card_info[] = [
                    'name' => $val['bank_name'],
                    'bank_card_num' => $val['card_num']
                ];
            }
        }
        return $info = [
            'bank_card_info' => $bank_card_info,
            'credit_card_info' => $credit_card_info
        ];
    }

    /**
     * 获取列表
     * status 1 借款中 2 完成 借款状态
     * type 细分状态 1 待还 5 逾期 3 正常还款 4 全部还清
     * 用户名
     */
    public static function getRepayListExport($status,$type,$name){

        $back = new RepaySummary();
        $back->setConnection('backend');
        $info =$back->query()
            ->select('repay_records.id','repay_records.summary_id','repay_records.uid','user_cert_ocrs.name as name','user_cert_ocrs.num as num','repay_records.status','repay_records.pay_off','normal_date','repay_date','users.phone_num','users.source')
            ->where('current_repay',RepaySummary::CURRENT_REPAY_ONE)//获取当前的操作期数
            ->where('user_cert_ocrs.is_valid',UserCertOcr::IS_VALID)
            ->leftjoin('user_cert_ocrs','user_cert_ocrs.user_id','repay_summaries.uid')
            ->leftjoin('users','users.id','repay_summaries.uid')
            ->leftjoin('repay_records',function($q){
                $q->On('repay_records.summary_id', '=', 'repay_summaries.id')->On('repay_records.period', '=', 'repay_summaries.period');
            })
            ->when($status, function ($query) use ($status) {
                return $query->where('repay_summaries.status', $status);
            })
            ->when($name, function ($query) use ($name) {
                return $query->where('user_cert_ocrs.name', $name);
            })
            ->when($type, function ($query) use ($type) {
                switch ($type){//1 待还 5 逾期 2 正常还款 4 全部还清
                    case RepayRecordMoney::TYPE_ONE:
                        $query->whereIn('repay_records.status',[RepayRecord::STATUS_ONE,RepayRecord::STATUS_TWO,RepayRecord::STATUS_THREE]);
                        break;
                    case RepayRecordMoney::TYPE_FIVE:
                        $query->where('repay_records.normal_date','<=',Carbon::now()->toDateString());
                        $query->where('repay_records.status','<>',RepayRecord::STATUS_FOUR);
                        break;
                    case RepayRecordMoney::TYPE_TWO:
                        $query->where('repay_records.pay_off','=',RepayRecord::PAY_OFF_ONE);
                        $query->where('repay_summaries.status','=',RepaySummary::STATUS_TWO);
                        break;
                    case RepayRecordMoney::TYPE_FOUR:
                        $query->where('repay_records.pay_off','=',RepayRecord::PAY_OFF_TWO);
                        $query->where('repay_summaries.status','=',RepaySummary::STATUS_TWO);
                        break;
                }
            });
        $data = $info->get()->toArray();
        $data = self::getDataExport($data);
        return $data;
    }

    protected static function getDataExport($data){
        if(!$data){
            return [];
        }
        foreach ($data as $k => &$v){
            $summaryInfo = self::select('status','uid','loan_id','amount','period_count')->where('id',$v['summary_id'])->first();
            $v['summary_status'] = RepaySummary::$FULL_STATUS[$summaryInfo['status']];
            $v['count'] = self::where('uid',$summaryInfo['uid'])->count();
            $v['loan_id'] = $summaryInfo['loan_id'];
            $v['amount'] = $summaryInfo['amount'];
            $v['period_count'] = $summaryInfo['period_count'];

            //判断type的状态
            if($v['status'] != RepayRecord::STATUS_FOUR){
                $v['type'] = RepayRecordMoney::$TYPE_ENUM[RepayRecordMoney::TYPE_ONE];
            }elseif(count_days(Carbon::now()->toDateString(),$v['normal_date']) > 0 && $v['status'] == RepayRecord::STATUS_FOUR && $v['pay_off'] == RepayRecord::PAY_OFF_ONE){
                $v['type'] = RepayRecordMoney::$TYPE_ENUM[RepayRecordMoney::TYPE_FIVE];
            }elseif($v['pay_off'] == RepayRecord::PAY_OFF_ONE && $v['status'] == RepayRecord::STATUS_FOUR){
                $v['type'] = RepayRecordMoney::$TYPE_ENUM[RepayRecordMoney::TYPE_TWO];
            }elseif($v['pay_off'] == RepayRecord::PAY_OFF_TWO && $v['status'] == RepayRecord::STATUS_FOUR){
                $v['type'] = RepayRecordMoney::$TYPE_ENUM[RepayRecordMoney::TYPE_FOUR];
            }
            unset($v['summary_id']);
            unset($v['status']);
            unset($v['pay_off']);
        }
        return $data;
    }








}